const mysql = require('mysql2');

const mysqlConnection = mysql.createConnection({
    host: '8.134.182.240',
    user: 'hanxiaoxin',
    password: 'apusic$2021',
    database: 'IOT',
});

function get_time() {
    const date = new Date()
    return date.toLocaleString('zh-cn').replaceAll('/', '-')
}

function query_device_exist(device_id) {
    const sql = `select id from device where device_id = '${device_id}'`;
    //console.log(sql);

    return new Promise(resolve => {
        mysqlConnection.query(
            sql,
            function (err, results) {
                if (results.length > 0) {
                    resolve(true)
                    return;
                }
                resolve(false)
            }
        );
    });
}

function insert_new_device(event) {
    const { device_id, info = {}, type, description = '' } = event;

    if (!device_id) {
        return;
    }

    const create_time = get_time();
    const update_time = create_time;
    const status = 1;
    const protocol = 'websocket';
    const info_str = JSON.stringify(info)

    const deviceInfo = info["device_info"] || {}
    const ipv4 = deviceInfo["ifconfig"] || {}

    const ipv4_str = JSON.stringify(ipv4)

    const sql1 = 'INSERT INTO device(device_id,info,create_time,update_time,status,type,description, protocol, ipv4) values('
    const sql2 = `'${device_id}','${info_str}', '${create_time}', '${update_time}', ${status}, '${type}', '${description}', '${protocol}', '${ipv4_str}'`;
    const sql3 = ');';
    const sql = sql1 + sql2 + sql3;
    //console.log(sql);

    return new Promise(resolve => {
        mysqlConnection.query(
            sql,
            function (err, results) {
                resolve(1)
            }
        );
    });
}

function update_device_record(event) {
    const { device_id, info = {}, type, description } = event;

    if (!device_id) {
        return;
    }

    const deviceInfo = info["device_info"] || {}
    const ipv4 = deviceInfo["ifconfig"] || {}
    const ipv4_str = JSON.stringify(ipv4)

    const device_config = info["device_config"] || {}
    const firmware_config = info["firmware_config"] || {}
    const version = firmware_config["version"] || "-"
    //console.log(version)

    const update_time = get_time();
    const status = 1;
    const protocol = 'websocket';

    let sql1 = `UPDATE device set update_time = '${update_time}', status = ${status}, protocol = '${protocol}',`
    const condition = ` where device_id = '${device_id}'`;

    if (type) {
        sql1 += ` type = '${type}',`
    }

    if (ipv4_str) {
        sql1 += ` ipv4 = '${ipv4_str}',`
    }

    if (version) {
        sql1 += ` version = '${version}',`
    }

    if (description) {
        sql1 += `and description = '${description}',`
    }

    if (info) {
        const info_str = JSON.stringify(info)
        sql1 += `info = '${info_str}',`
    }

    sql1 = sql1.substring(0, sql1.length - 1)

    const sql = sql1 + condition;

    return new Promise(resolve => {
        mysqlConnection.query(
            sql,
            function (err, results) {
                resolve(1)
            }
        );
    });
}

module.exports = {
    query_device_exist,
    insert_new_device,
    update_device_record,
}